# JWTutil.py
import base64

import jwt
import yaml
from datetime import datetime
import nacos
from fastapi import HTTPException, status
import base64

class JWTUtil:

    def get_signing_key(self):
        # 假设密钥是 Base64 编码的字符串
        return base64.b64decode(self.SECRET_KEY)

    def __init__(self):
        # 初始化NACOS客户端
        self.nacos_client = nacos.NacosClient("localhost:8850", namespace="public")
        # 获取JWT配置
        config = self.nacos_client.get_config("api.yaml", "DEFAULT_GROUP")
        jwt_config = yaml.safe_load(config).get('app', {}).get('jwt', {})

        self.SECRET_KEY = jwt_config.get('secret-key')
        self.ALGORITHM = "HS512"
        self.EXPIRATION = jwt_config.get('expiration', 86400000)  # 默认10天

    def verify_token(self, token: str) -> bool:
        """
        验证JWT有效性
        :param token: JWT字符串
        :return: 验证结果
        """
        try:
            payload = jwt.decode(
                token,
                self.SECRET_KEY,
                algorithms=[self.ALGORITHM]
            )
            return True
        except jwt.ExpiredSignatureError:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token过期"
            )
        except jwt.InvalidTokenError:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效Token"
            )

    def extract_user_id(self, token: str) -> str:
        """
        从JWT中提取用户ID
        :param token: JWT字符串
        :return: 用户ID
        """
        try:
            payload = jwt.decode(
                token,
                self.SECRET_KEY,
                algorithms=[self.ALGORITHM]
            )
            user_id = payload.get('sub')
            if not user_id:
                raise ValueError("Token 不包含用户标识 (sub)")
            return user_id
        except jwt.PyJWTError:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无法解析用户信息"
            )

    @staticmethod
    def create_token(user_id: str) -> str:
        """
        创建新Token（示例方法）
        :param user_id: 用户ID
        :return: JWT字符串
        """
        # 实际应结合业务逻辑实现完整签发功能
        return jwt.encode(
            {
                "sub": user_id,
                "exp": datetime.utcnow().timestamp() + 86400000
            },
            JWTUtil().SECRET_KEY,
            algorithm=JWTUtil().ALGORITHM
        )
